import React from 'react';
import { generationManager } from '@/utils/generation';

const POLL_INTERVAL_MS = 2500;

const GenerationTaskHost: React.FC = () => {
  React.useEffect(() => {
    let timer: number | undefined;
    const tick = async () => {
      await generationManager.pollOnce();
      // 仅当仍有待处理任务时继续轮询
      const hasPending = generationManager.getState().pendingTaskIds.length > 0;
      if (hasPending) {
        timer = window.setTimeout(tick, POLL_INTERVAL_MS);
      } else {
        timer = undefined as any;
      }
    };

    // 首次进入页面时，如存在历史未完成任务，立即轮询一次
    if (generationManager.getState().pendingTaskIds.length > 0) {
      tick();
    }

    // 当有新任务加入时自动启动轮询
    const unsubscribe = generationManager.subscribe(() => {
      const hasPending = generationManager.getState().pendingTaskIds.length > 0;
      if (hasPending && !timer) {
        timer = window.setTimeout(tick, POLL_INTERVAL_MS);
      }
    });

    return () => {
      if (timer) window.clearTimeout(timer);
      unsubscribe();
    };
  }, []);

  return null;
};

export default GenerationTaskHost;


